package com.yty.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yty.order.entity.AccountInfo;
import com.yty.order.entity.DeDuplication;
import com.yty.order.mapper.AccountInfoMapper;
import com.yty.order.mapper.DeDuplicationMapper;
import com.yty.order.service.IAccountInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yty.order.service.IDeDuplicationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yegang
 * @since 2022-06-24
 */
@Service
@Slf4j
public class AccountInfoServiceImpl extends ServiceImpl<AccountInfoMapper, AccountInfo> implements IAccountInfoService {

    @Autowired
    private AccountInfoMapper accountInfoMapper;

    @Autowired
    private DeDuplicationMapper deDuplicationMapper;

    @Autowired
    private IDeDuplicationService deDuplicationService;

    /**
     * 消费消息，更新本地事务，添加金额
     */
    @Override
    @Transactional
    public void addAccountInfoBalance(AccountInfo accountInfo) {
        log.info("bank2更新本地账号，账号：{},金额：{}",accountInfo.getAccountNo(),accountInfo.getAmount());
        //幂等校验
        int count = deDuplicationMapper.selectCount(new QueryWrapper<DeDuplication>().lambda()
                .eq(DeDuplication::getTxNo,accountInfo.getTxNo())
                .eq(DeDuplication::getIsSuccess,true));
        if (count > 0){
            return;
        }
        //执行更新
        AccountInfo a = getOne(new QueryWrapper<AccountInfo>().lambda().eq(AccountInfo::getAccountNo,accountInfo.getAccountNo()));
        if (a == null){
            throw new RuntimeException("账户不存在！");
        }
        a.setAccountBalance(accountInfo.getAmount().add(a.getAccountBalance()));
        updateById(a);
        log.info("更新本地事务执行成功，本次事务号: {}", accountInfo.getTxNo());
    }
}
